package com.demo.springmvc底层演示.demo1;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

public class Test {
	
	public static void main(String[] args) throws Exception {
		AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(WebConfig.class);
		// 解析@RequestMapping以及派生注解，生成路径与控制器方法的映射关系，在初始化时就生成
		RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
		Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
		handlerMethods.forEach((k, v) -> {
			System.out.println(k + "=" + v);
		});
		
		// 调用控制器方法
		MyRequestMappingHandlerAdapter handlerAdapter = context.getBean(MyRequestMappingHandlerAdapter.class);
		MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test1");
		MockHttpServletResponse response = new MockHttpServletResponse();
		handlerAdapter.invokeHandlerMethod(request, response, (HandlerMethod)handlerMapping.getHandler(request).getHandler());
		byte[] content = response.getContentAsByteArray();
		System.out.println(new String(content, "utf-8"));
		
		// 参数解析器
		List<HandlerMethodArgumentResolver> resolvers = handlerAdapter.getArgumentResolvers();
		for (HandlerMethodArgumentResolver resolver : resolvers) {
			System.out.println(resolver);
		}
		// 返回值处理器
		List<HandlerMethodReturnValueHandler> returnHandlers = handlerAdapter.getReturnValueHandlers();
		for (HandlerMethodReturnValueHandler returnHandler : returnHandlers) {
			System.out.println(returnHandler);
		}
	}

}
